package net.roobook.cms.modules.admin.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import net.roobook.cms.common.annotation.Log;
import net.roobook.cms.common.annotation.Log.OperatorType;
import net.roobook.cms.common.entity.ResResult;
import net.roobook.cms.common.entity.SearchEntity;
import net.roobook.cms.common.entity.StateCodeEnum;
import net.roobook.cms.common.exception.CmsException;
import net.roobook.cms.common.exception.XssAndSqlException;
import net.roobook.cms.common.web.BaseController;
import net.roobook.cms.modules.admin.entity.Category;
import net.roobook.cms.modules.admin.entity.SysSetting;
import net.roobook.cms.modules.admin.service.CategoryService;
import net.roobook.cms.modules.admin.service.SysSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;
import java.util.List;

/**
 * @author cos
 * @email 327878610@qq.com
 * @link https://roobook.net
 * @Description 栏目管理
 * @date 2023/9/26 16:50
 **/
@Controller
@RequestMapping("/admin/category")
public class CategoryController extends BaseController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SysSettingService sysSettingService;
    @Log(operType = OperatorType.PAGE, module = "栏目管理", content = "栏目分页列表")
    @RequestMapping({"","/list"})
    public String list(Model model, SearchEntity params) {
        PageInfo<Category> page = categoryService.queryListByPage(params);
        model.addAttribute("page", page);
        return "admin/category/list";
    }

    @Log(operType = OperatorType.SELECT, module = "栏目管理", content = "加载下级栏目")
    @RequestMapping(value = "/loadSon", method = RequestMethod.GET)
    public void loadSon(String id) {
        List<Category> list = categoryService.selectByParentId(id);
        ResResult result = ResResult.Factory.newInstance(Boolean.TRUE,
                StateCodeEnum.HTTP_SUCCESS.getCode(), list,
                StateCodeEnum.HTTP_SUCCESS.getDescription());
        this.outJson(result);
    }


    @Log(operType = OperatorType.OTHER, module = "栏目管理", content = "添加栏目页面")
    @RequestMapping("/toAdd")
    public String toAdd(Model model,String id) {
        Category category = null;
        if(id.equals("-1")) {
            category = new Category();
            category.setParentId("-1");
            category.setLevel("1");
            category.setCnname("顶级栏目");
        }else {
            category = categoryService.queryEntityById(id);
            category.setLevel((Integer.parseInt(category.getLevel())+1)+"");
        }
        model.addAttribute("category", category);
        return "admin/category/add";
    }


    @Log(operType = OperatorType.INSERT, module = "栏目管理", content = "添加栏目")
    @RequestMapping("/add")
    public String add(Category category) throws CmsException {
        category.setId(IdUtil.getSnowflakeNextIdStr());
        category.setCode(RandomUtil.randomString(8));
        category.setLevel(category.getParentId().equals("-1") ? "1" : category.getLevel());
        category.setParentId(StrUtil.isBlank(category.getParentId())? "-1" : category.getParentId());
        category.setCreateBy(getUserId());
        category.setCreateTime(new Date());
        if(!"-1".equals(category.getParentId())) {
            Category parent = categoryService.queryEntityById(category.getParentId());
            category.setCatSeq(parent.getCatSeq() + "." + category.getCode());
        }else {
            category.setCatSeq("." + category.getCode());
        }

        String coverTemp = StrUtil.isBlank(category.getCoverTemp()) ? "" : category.getCoverTemp();
        String listTemp = StrUtil.isBlank(category.getListTemp()) ? "" : category.getListTemp();
        String articleTemp = StrUtil.isBlank(category.getArticleTemp()) ? "" : category.getArticleTemp();

        if(coverTemp.contains("../") || coverTemp.contains("..\\")) {
            throw new XssAndSqlException(
                    StateCodeEnum.XSS_SQL_EXCEPTION.getCode(),
                    StateCodeEnum.XSS_SQL_EXCEPTION.getDescription(),
                    "栏目封面模板文件名疑似不安全，详情：" + category.getCoverTemp());
        }
        if(listTemp.contains("../") || listTemp.contains("..\\")) {
            throw new XssAndSqlException(
                    StateCodeEnum.XSS_SQL_EXCEPTION.getCode(),
                    StateCodeEnum.XSS_SQL_EXCEPTION.getDescription(),
                    "栏目列表模板文件名疑似不安全，详情：" + category.getListTemp());
        }

        //处理模版
        if(StrUtil.isNotBlank(category.getCoverTemp()) && !category.getCoverTemp().startsWith("/")) {
            category.setCoverTemp("/" + category.getCoverTemp());
        }
        if(StrUtil.isNotBlank(category.getListTemp()) && !category.getListTemp().startsWith("/")) {
            category.setListTemp("/" + category.getListTemp());
        }
        if(StrUtil.isNotBlank(category.getArticleTemp()) && !category.getArticleTemp().startsWith("/")) {
            category.setArticleTemp("/" + category.getArticleTemp());
        }
        categoryService.add(category);
        return "redirect:/admin/category/list";
    }

    @Log(operType = OperatorType.OTHER, module = "栏目管理", content = "修改栏目页面")
    @RequestMapping("/toEdit")
    public String toEdit(Model model,String id) {
        Category category = categoryService.queryEntityById(id);
        if(category.getParentId().equals("-1")) {
            category.setParentName("顶级栏目");
        }else {
            Category category2 = categoryService.queryEntityById(category.getParentId());
            category.setParentName(category2.getCnname());
        }

        SysSetting system = sysSettingService.getSystem();
        model.addAttribute("category", category);
        model.addAttribute("system", system);
        return "admin/category/edit";
    }

    @Log(operType = OperatorType.UPDATE, module = "栏目管理", content = "修改栏目")
    @RequestMapping(value ="/edit")
    public String edit(Category category) throws CmsException {
        category.setUpdateBy(getUserId());
        category.setUpdateTime(new Date());

        String coverTemp = StrUtil.isBlank(category.getCoverTemp()) ? "" : category.getCoverTemp();
        String listTemp = StrUtil.isBlank(category.getListTemp()) ? "" : category.getListTemp();
        if(coverTemp.contains("../") || coverTemp.contains("..\\")) {
            throw new XssAndSqlException(
                    StateCodeEnum.XSS_SQL_EXCEPTION.getCode(),
                    StateCodeEnum.XSS_SQL_EXCEPTION.getDescription(),
                    "栏目封面模板文件名疑似不安全，详情：" + category.getCoverTemp());
        }
        if(listTemp.contains("../") || listTemp.contains("..\\")) {
            throw new XssAndSqlException(
                    StateCodeEnum.XSS_SQL_EXCEPTION.getCode(),
                    StateCodeEnum.XSS_SQL_EXCEPTION.getDescription(),
                    "栏目列表模板文件名疑似不安全，详情：" + category.getListTemp());
        }

        //处理模版
        if(StrUtil.isNotBlank(category.getCoverTemp()) && !category.getCoverTemp().startsWith("/")) {
            category.setCoverTemp("/" + category.getCoverTemp());
        }
        if(StrUtil.isNotBlank(category.getListTemp()) && !category.getListTemp().startsWith("/")) {
            category.setListTemp("/" + category.getListTemp());
        }
        int num = categoryService.update(category);
        return "redirect:/admin/category/list";
    }


    @Log(operType = OperatorType.DELETE, module = "栏目管理", content = "删除栏目")
    @RequestMapping(value ="/delete")
    public String delete(String id){
        int num = categoryService.delete(id);
        return "redirect:/admin/category/list";
    }

}
